package com.example.webdome.controller;

import com.example.webdome.pojo.LoginRequest;
import com.example.webdome.pojo.Result;
import com.example.webdome.pojo.User;
import com.example.webdome.service.UserService;
import com.example.webdome.util.getCookie;
import com.example.webdome.util.urlCount;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private getCookie getCookie;
    @Resource
    private urlCount Count;

    //登录接口
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request) {
        String uri = request.getRequestURI();
        Count.recordUrlCount(uri);
        return userService.login(loginRequest, response);
    }

    //退出登录接口
    @GetMapping("/outLogin")
    public Result outLogin(HttpServletRequest request, HttpServletResponse response) {
        String cookieValue = request.getHeader("Cookie");
        String token = getCookie.getCookieValue(cookieValue);
        try {
            if (token != null) {
                return userService.outLogin(token, response);
            }
        } catch (Exception e) {
            return Result.failed("退出失败！：" + e.getMessage());
        }
        return Result.failed("请先登录！");
    }

    //注册接口
    @PostMapping("/register")
    public Result register(@RequestBody User user, @RequestParam String code
            , HttpServletRequest request) {
        String uri = request.getRequestURI();
        Count.recordUrlCount(uri);
        return userService.register(user, code);
    }

    //找回密码接口
    @PostMapping("/findPassword")
    public Result findPassWord(@RequestParam String email, @RequestBody User user, @RequestParam String code
            , HttpServletRequest request) {
        String uri = request.getRequestURI();
        Count.recordUrlCount(uri);
        return userService.findPassWord(email, user, code);
    }

    //统计登录的用户
    @GetMapping("/Count")
    public Result tokenCount() {
        return userService.tokenCount();
    }

}
